package com.itheima.server.service;

import com.itheima.api.UserInfoApi;
import com.itheima.autoconfig.template.AipTemplate;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.domain.UserInfo;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Resource
    private OssTemplate ossTemplate;

    @Resource
    private AipTemplate aipTemplate;


    /**
     * 保存用户信息
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 上床头像
     * @param headPho
     * @param id
     */
    public void uploadHeadPho(MultipartFile headPho, Long id) {

        try {
            //上传到阿里云
            String path = ossTemplate.upload(headPho.getOriginalFilename(), headPho.getInputStream());
            //上传到百度人脸检测
            boolean detect = aipTemplate.detect(path);
            if (!detect){
                //去阿里云删除图片
                ossTemplate.delete(path);
                throw new RuntimeException("不存在人脸");
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(path);
            userInfoApi.update(userInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询用户信息
     * @param userID
     * @return
     */
    public UserInfoVo getById(Long userID) {
        UserInfo userInfo = userInfoApi.getById(userID);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        if(userInfo.getAge() != null) {
            //返回age类型不同
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    /**
     * 修改用户信息
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

}
